import React, { useEffect, useState } from 'react';
import {
  Menu,
  Input,
  Select,
  DatePicker,
  Pagination,
  Table,
  message,
} from 'antd';
import { history } from 'umi';
import styles from './index.css';
import 'moment/locale/zh-cn';

import { pageConditionQueryByCreatorId } from '../../api/request';

const { Option } = Select;
const { RangePicker } = DatePicker;

export default function Activity(props) {
  //表格列定义
  const columns = [
    {
      title: '活动名称',
      dataIndex: 'activityName',
      key: 'activityName',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
    },
    {
      title: '活动时间',
      dataIndex: 'activityDate',
      key: 'activityDate',
      render: (text, record) => (
        <p>
          {record.startDate} - {record.endDate}
        </p>
      ),
    },
    {
      title: '所属分行',
      dataIndex: 'bankCode',
      key: 'bankCode',
    },
    {
      title: '状态',
      dataIndex: 'activityStatus',
      key: 'activityStatus',
      render: (text, record) => (
        <>{RecognitionStatus(record.isDraft, record.activityStatus)}</>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => {
        if (record.isDraft) {
          return (
            <>
              <span
                className={styles.viewDetails}
                onClick={() => changeDraft(record.activityBasicId)}
              >
                修改
              </span>
              &nbsp;&nbsp;
              <span className={styles.viewDetails}>删除</span>
            </>
          );
        } else {
          return (
            <>
              <span
                className={styles.viewDetails}
                onClick={() => {
                  history.push({
                    pathname: `${props.match.path}/detail`,
                    state: { activityBasicId: record.activityBasicId },
                  });
                }}
              >
                详情
              </span>
            </>
          );
        }
      },
    },
  ];

  const RecognitionStatus = (isDraft, activityStatus) => {
    if (isDraft) return <span style={{ color: '#abacac' }}>草稿</span>;
    switch (activityStatus) {
      case 1:
        return <span style={{ color: '#0C9682' }}>待审核</span>;
      case 2:
        return <span style={{ color: '#862DFB' }}>进行中</span>;
      case 3:
        return <span style={{ color: '#A0A0A0' }}>未开始</span>;
      case 4:
        return <span style={{ color: '#ff0e22' }}>已驳回</span>;
      case 5:
        return <span style={{ color: '#FE4D5C' }}>已结束</span>;
      case 6:
        return <span style={{ color: '#FE4D5C' }}>已关闭</span>;
      default:
        return <span style={{ color: '#fb0000' }}>错误！</span>;
    }
  };

  //页码
  const [page, setPage] = useState(1);
  //页显示条数
  const [pageSize, setPageSize] = useState(10);
  //活动名称模糊查询传值
  const [activityName, setActivityName] = useState('');
  //活动开始时间
  const [queryStartDate, setQueryStartDate] = useState();
  //活动结束时间
  const [queryEndDate, setQueryEndDate] = useState();
  //活动状态值传参
  const [activityStatus, setActivityStatus] = useState([]);
  //是否草稿
  const [isDraft, setiIsDraft] = useState(0);

  //活动管理控制目录显示
  const [selectedKeys, setSelectedKeys] = useState(['All']);
  //表格请求数据
  const [activityData, setActivityData] = useState([]);
  // 返回数据库中符合条件的数据总条数
  const [total, setTotal] = useState(0);

  /*activityStatus和selectedKeys基本结构相同，但是activityStatus是请求的参数，不能出现有'All'的情况，所以分开他们的功能，activityStatus作为请求时的参数，selectedKeys作为控制目录激活情况的数组 */

  useEffect(() => {
    requestActicityTableInfo();
  }, [page, pageSize, activityStatus]);

  useEffect(() => {
    let newKeys = [...selectedKeys];
    if (selectedKeys.indexOf('All') != -1) {
      newKeys.splice(selectedKeys.indexOf('All'), 1);
    }
    if (selectedKeys.indexOf('Draft') != -1) {
      newKeys.splice(selectedKeys.indexOf('Draft'), 1);
    }
    setActivityStatus(newKeys);
  }, [selectedKeys]);

  // 请求活动列表信息函数，方便多次调用
  const requestActicityTableInfo = () => {
    //为了未选择的参数不在请求体中，进行判断赋新值
    let requestInfo = {};
    if (page) requestInfo.page = page;
    if (pageSize) requestInfo.pageSize = pageSize;
    if (activityName) requestInfo.activityName = activityName;
    if (queryStartDate) requestInfo.queryStartDate = queryStartDate;
    if (queryEndDate) requestInfo.queryEndDate = queryEndDate;
    if (activityStatus.length != 0) requestInfo.activityStatus = activityStatus;
    if (isDraft) requestInfo.isDraft = isDraft;
    pageConditionQueryByCreatorId(requestInfo).then((res) => {
      // console.log(res.data);
      if (res.data.code == 200) {
        res.data.data.rows.forEach((element) => {
          element.key = element.activityBasicId;
        });
        setTotal(res.data.data.total);
        setActivityData(res.data.data.rows);
      } else {
        message.error(res.data.message);
      }
    });
  };

  //选择目录状态控制
  const changeActivityStatus = (argument) => {
    if (selectedKeys.length == 1 && argument.key == selectedKeys[0]) return;
    let newKeys = [...selectedKeys];
    if (argument.key == 'All' && selectedKeys.indexOf('All') == -1) {
      //点中全部时重置目录样式与参数
      setiIsDraft(0);
      setSelectedKeys(['All']);
      setActivityStatus([]);
      return;
    } else if (argument.key != 'All' && selectedKeys.indexOf('All') != -1) {
      newKeys.splice(selectedKeys.indexOf('All'), 1);
    }
    if (selectedKeys.indexOf(argument.key) == -1) {
      newKeys.push(argument.key);
    } else {
      newKeys.splice(selectedKeys.indexOf(argument.key), 1);
    }
    setSelectedKeys(newKeys);
    if (argument.key == 'Draft') {
      if (isDraft) {
        setiIsDraft(0);
      } else {
        setiIsDraft(1);
      }
    }
  };

  //页码的修改回调
  const changePage = (newPage, newPageSize) => {
    // console.log('page',page);
    // console.log('pageSize',pageSize);
    if (pageSize == newPageSize) {
      setPage(newPage);
    } else {
      setPage(1);
      setPageSize(newPageSize);
    }
  };
  //名称查询框的修改回调，作用为绑定
  const changeActivityName = (e) => {
    setActivityName(e.target.value);
  };
  //活动开始结束时间变化的回调
  const changeActivityDate = (dates, dateStrings) => {
    setQueryStartDate(dateStrings[0]);
    setQueryEndDate(dateStrings[1]);
  };

  //跳转修改传参
  const changeDraft = (id) => {
    history.push({
      pathname: `${props.match.path}/add`,
      state: { activityBasicId: id },
    });
  };
  //删除传参

  return (
    <div className={styles.activity}>
      <h1 className={styles.title}>活动管理</h1>
      <Menu
        onClick={changeActivityStatus}
        mode="horizontal"
        multiple={true}
        selectedKeys={selectedKeys}
      >
        <Menu.Item key="All">全部</Menu.Item>
        <Menu.Item key="1">待审核</Menu.Item>
        <Menu.Item key="2">进行中</Menu.Item>
        <Menu.Item key="3">未开始</Menu.Item>
        <Menu.Item key="4">已驳回</Menu.Item>
        <Menu.Item key="5">已结束</Menu.Item>
        <Menu.Item key="Draft">草稿</Menu.Item>
      </Menu>
      <div className={styles.queryBox}>
        <div className={styles.queryInput}>
          <p>活动名称：</p>
          <Input
            placeholder="请输入"
            className={styles.activityName}
            allowClear={true}
            value={activityName}
            onChange={changeActivityName}
          />
          <p>活动时间：</p>
          <RangePicker
            className={styles.activityDate}
            inputReadOnly={true}
            onChange={changeActivityDate}
          />
          <input
            type="button"
            value="+ 添加活动"
            className={styles.activityQueryBtn}
            style={{ backgroundColor: '#1a267b', color: '#ffffff' }}
            onClick={() => {
              history.push(`${props.match.path}/add`);
            }}
          />
        </div>
        <div className={styles.queryBtn}>
          <input
            type="button"
            value="取消"
            className={styles.activityQueryBtn}
          />
          <input
            type="button"
            value="确认"
            className={styles.activityQueryBtn}
            style={{ backgroundColor: '#1a267b', color: '#ffffff' }}
            onClick={() => requestActicityTableInfo()}
          />
        </div>
      </div>
      <Table
        columns={columns}
        dataSource={activityData}
        pagination={false}
        className={styles.activityTable}
        scroll={{ y: 510, scrollToFirstRowOnChange: true }}
      />
      <Pagination
        className={styles.tablePagination}
        showSizeChanger={true}
        showQuickJumper={true}
        defaultCurrent={page}
        current={page}
        pageSize={pageSize}
        total={total}
        onChange={changePage}
        pageSizeOptions={[10, 20, 50]}
        showTotal={(total) => `共${total}条`}
      />
    </div>
  );
}
